/*
 * Materiale didattico per corso sulle Applicazioni Internet 
 * 
 * Copyright (c) 2005-2008 Link.it srl (http://link.it). All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * @author Lorenzo Nardi (nardi80@gmail.com)
 */


package isi.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;



public class ClientXML {

    public final static void main(String[] args) throws Exception {
    	
    	
    	String carrello = null;
    	HttpClient httpclient = new DefaultHttpClient();
    	
    		//Faccio una serie di ordini e richiamo la solita sessione  
    	for(int i=0 ; i < 1 ; i++){
    		String queryString = "http://localhost:8080/shop/buy/";
    	
    		//Prepariamo la richiesta
    		HttpPost httppost = new HttpPost(queryString); 
    		
    		//Costruisco il DOM dell'ordine
    		Document ordine = getOrdine(i);
    		
    		//Converto il DOM in stringa
    		String ordineXML = toString(ordine);
    		StringEntity content = new StringEntity(ordineXML);
    		content.setContentType("text/xml");
    		httppost.setEntity(content);
    		
        	//Eseguiamo la richiesta e prendiamo la risposta
        	HttpResponse response = httpclient.execute(httppost);
        	 
        	//Stampiamo Status Line
        	System.out.println("Ordine " + i + " eseguita con esito : " +  response.getStatusLine());
    	}
    }
    
    private static Document getOrdine(int i){
    	String[] articoli = {"SONYPS3","NINTWII","MICXBOX"};
        try{
            //Crea un istanza di DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //Ottieni il DocumentBuilder
            DocumentBuilder parser = factory.newDocumentBuilder();
            //Crea un DOM Document vuoto
            Document doc = parser.newDocument();
            // Creo l'elemento ordine con l'attributo corriere e lo appendo al documento
            Element ordine = doc.createElementNS("http://www.shop.com/ns", "ns:ordine");
            //ordine.setAttribute("corriere", "DHL");
            doc.appendChild(ordine);
            
            //Creo l'elemento articolo e lo aggiungo all'ordine
            Element articolo = doc.createElement("ns:articolo");
            Element nome = doc.createElement("ns:nome");
            Element quantita = doc.createElement("ns:quantita");
            nome.appendChild(doc.createTextNode(articoli[i]));
            quantita.appendChild(doc.createTextNode( ((new Random()).nextInt(10) +1) + ""));
            articolo.appendChild(nome);
            articolo.appendChild(quantita);
            ordine.appendChild(articolo);
            return doc;
        }
        catch(Exception e){
              System.out.println(e.getMessage());
        }
        return null;
    }
    
    
    
    private static String toString(Document doc){
    	try{
	    	DOMSource domSource = new DOMSource(doc);
	        StringWriter writer = new StringWriter();
	        StreamResult result = new StreamResult(writer);
	        TransformerFactory tf = TransformerFactory.newInstance();
	        Transformer transformer = tf.newTransformer();
	        transformer.transform(domSource, result);
	        return writer.toString();
    	}
    	catch(TransformerConfigurationException e){
    		e.printStackTrace();
    	}
    	catch(TransformerException e){
    		e.printStackTrace();
    	}
    	return "";
    }
}

